<template>
  <view class="page">

    <!-- 图片滑动切换 -->
    <swiper circular :current="currentIndex" @change="previewChange" class="swiper">
      <swiper-item v-for="(item, index) in dataList" :key="item._id" class="swiper-item">
        <image v-if="readImgs.includes(index)" @click="maskChange" :src="item.picUrl" mode="scaleToFill"
          class="image" />
      </swiper-item>
    </swiper>

    <!-- 显示返回等等按钮、时间、日期的遮罩层 -->
    <view class="mask" v-show="maskState">

      <com-arrowLeft></com-arrowLeft>

      <view class="count">
        <text>{{ currentIndex + 1 }} / {{ listCount }}</text>
      </view>

      <view class="time">
        <uni-dateformat :date="time" format="hh:mm"></uni-dateformat>
      </view>

      <view class="date">
        <uni-dateformat :date="time" format="MM月dd号"></uni-dateformat>
      </view>

      <view class="footer">
        <view @click="onInfoPopup" class="item">
          <uni-icons type="info" size="28"></uni-icons>
          <view class="title">
            <text>信息</text>
          </view>
        </view>
        <view @click="onScorePopup" class="item">
          <uni-icons type="star" size="28"></uni-icons>
          <view class="title">
            <text>{{ currentInfo?.score }}分</text>
          </view>
        </view>
        <view @click="onDownload" class="item">
          <uni-icons type="download" size="28"></uni-icons>
          <view class="title">
            <text>下载</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 壁纸信息的弹窗 -->
    <uni-popup ref="infoPopup" type="bottom" :safe-area="false">
      <view class="info-Popup">

        <view class="head">
          <view class="empty"></view>
          <view class="title">
            <text>壁纸信息</text>
          </view>
          <view @click="onInfoClose" class="close">
            <uni-icons type="closeempty" size="20"></uni-icons>
          </view>
        </view>

        <scroll-view class="scroll-view" scroll-y>
          <view class="content">
            <view class="row">
              <view class="label">壁纸ID：</view>
              <text user-select class="value">{{ currentInfo?._id }}</text>
            </view>
            <view class="row">
              <view class="label">发布者：</view>
              <text user-select class="value">{{ currentInfo?.nickname }}</text>
            </view>
            <view class="row">
              <view class="label">评分：</view>
              <view class="value rating">
                <uni-rate readonly :touchable="false" :value="currentInfo?.score" />
                <text class="score">{{ currentInfo?.score }}分</text>
              </view>
            </view>
            <view class="row">
              <view class="label">摘要：</view>
              <text user-select class="value">{{ currentInfo?.description }}</text>
            </view>
            <view class="row">
              <view class="label">标签：</view>
              <view class="value tabs">
                <view v-for="value in currentInfo?.tabs" :key="value" class="tab">{{ value }}</view>
              </view>
            </view>
            <view class="copyright">
              <text>声明：本图片来用户投稿，非商业使用，用于免费学习交流，如侵犯了您的权益，您可以拷贝壁纸ID举报至平台，邮箱513894357@qq.com，管理将删除侵权壁纸，维护您的权益。</text>
            </view>
          </view>
        </scroll-view>
      </view>
    </uni-popup>

    <!-- 评分的弹窗 -->
    <uni-popup ref="scorePopup" type="center">
      <view class="score-Popup">
        <view class="head">
          <view class="empty"></view>
          <view class="title">
            <text>{{ isScore ? "评过分了~~" : "壁纸评分" }}</text>
          </view>
          <view @click="onScoreClose" class="close">
            <uni-icons type="closeempty" size="20"></uni-icons>
          </view>
        </view>

        <view class="content">
          <uni-rate allowHalf v-model="scoreValue" :disabled="isScore" disabled-color="#FFCA3E" />
          <text class="text">{{ scoreValue }}分</text>
        </view>

        <view class="footer">
          <button :disabled="!scoreValue || isScore" @click="subScore" plain size="mini" class="mini-btn">确认评分</button>
        </view>
      </view>
    </uni-popup>

    <!--  -->

  </view>
</template>


<script lang="ts" setup>
import { ref } from "vue";
import { onReady, onUnload, onLoad } from "@dcloudio/uni-app";
import { API } from "@/services/api";
import { useClassListStore } from "@/store";
const ClassListStore = useClassListStore();

const currentIndex = ref(0); // 当前预览图的索引
const currentInfo: any = ref(); // 当前预览图的详细信息
const readImgs = ref<number[]>([]); // 预览过的图片索引数组

// 监听页面加载 de 生命周期
onLoad((options) => {
  if (options) {
    currentIndex.value = ClassListStore.getItemIndexById(options.id);
    currentInfo.value = ClassListStore.getItemById(options.id);
    readImgsPush();
  }
});

// 监听页面初次渲染完成 de 生命周期
onReady(() => {
  getData();
  startTime();
});

// 监听页面卸载 de 生命周期
onUnload(() => {
  clearInterval(timer);
});

// 获取 store 中的列表数据
const dataList: any = ref([]);
const listCount = ClassListStore.listCount;
const getData = () => {
  dataList.value = ClassListStore.getAllItems().map(item => {
    return {
      ...item,
      picUrl: item.smallPicurl.replace("_small.webp", ".jpg")
    }
  });
};

// 预览图片滑动切换
const previewChange = (e: any) => {
  currentIndex.value = e.detail.current;
  currentInfo.value = ClassListStore.getItemByIndex(e.detail.current);
  readImgsPush();
};

// 预览过的图片索引添加至数组
const readImgsPush = () => {
  readImgs.value.push(
    currentIndex.value <= 0 ? listCount - 1 : currentIndex.value - 1,
    currentIndex.value,
    currentIndex.value >= listCount ? 0 : currentIndex.value + 1
  );
  readImgs.value = [...new Set(readImgs.value)]; // 数组快速去重
};

// 渲染层 de 显示 和 隐藏
const maskState = ref(true);
const maskChange = () => {
  maskState.value = !maskState.value
};

// 获取时间日期
const time = ref(Date.now());
// 每秒更新一次时间
let timer: number; // 每秒更新定时器
const startTime = () => {
  timer = setInterval(() => {
    time.value = Date.now();
  }, 1000);
};

// 信息弹出层 de 显示 和 隐藏
const infoPopup: any = ref(null);
const onInfoPopup = () => {
  infoPopup.value.open();
};

const onInfoClose = () => {
  infoPopup.value.close();
};

// 评分弹出层 de 显示 和 隐藏
const scorePopup: any = ref(null);
const onScorePopup = () => {
  if (currentInfo.value.userScore) {
    isScore.value = true;
    scoreValue.value = Number(currentInfo.value.userScore);
  } else {
    isScore.value = false;
    scoreValue.value = 0;
  }
  scorePopup.value.open();
};

const onScoreClose = () => {
  scorePopup.value.close();
  scoreValue.value = 0;
  isScore.value = false;
};

// 进行评分
const scoreValue = ref(0); // 评分（1~5）
const isScore = ref(false); // 是否已评分
const subScore = () => {
  console.log('~~~给出的评分是：' + scoreValue.value);
  let { classid, _id: wallId } = currentInfo.value;
  uni.showLoading({
    title: "提交中...",
  });
  API.setupScore(classid, wallId, String(scoreValue.value))
    .then(() => {
      uni.hideLoading();
      uni.showToast({
        title: "评分成功",
        icon: "success"
      });
      currentInfo.value.userScore = String(scoreValue.value);
      ClassListStore.updateItem(currentInfo.value);
      onScoreClose();
    })
    .catch(() => {
      console.log("~~~评分失败");
      onScoreClose();
    })
};

// 下载
const onDownload = async () => {
  try {
    uni.showLoading({
      title: "下载中...",
      mask: true
    });

    let { classid, _id: wallId } = currentInfo.value;
    let res: any = await API.downloadWall(classid, wallId);
    if (res.data.errCode != 0) throw res;

    let url = currentInfo.value.smallPicurl.replace("_small.webp", ".jpg");
    uni.getImageInfo({
      src: url,
      success: (success) => {
        console.log("~~~成功", success);
        uni.saveImageToPhotosAlbum({
          filePath: success.path,
          success: (success) => {
            uni.showToast({
              title: "保存成功，请到相册查看",
              icon: "none"
            })
          },
          fail: (err) => {
            if (err.errMsg == 'saveImageToPhotosAlbum:fail cancel') {
              uni.showToast({
                title: '保存失败，请重新点击下载',
                icon: "none"
              })
              return;
            }
            uni.showModal({
              title: '授权提示',
              content: '需要授权保存到相册',
              success: (success) => {
                if (success.confirm) {
                  uni.openSetting({
                    success: (success) => {
                      if (success.authSetting['scope.writePhotosAlbum']) {
                        uni.showToast({
                          title: "获取授权成功",
                          icon: "none"
                        })
                      } else {
                        uni.showToast({
                          title: "获取权限失败",
                          icon: "none"
                        })
                      }
                    }
                  })
                }
              },
            })
          },
          complete: () => {
            uni.hideLoading();
          }
        });
      },
      fail: (fail) => {
        console.log("~~~失败", fail);
        uni.hideLoading();
      },
    });
  } catch (err) {
    console.log(err);
    uni.hideLoading();
  }
};
</script>


<style lang="scss" scoped>
@use "style.scss";
</style>